/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package eu.vranckaert.calendar.widget;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.MonthDisplayHelper;
import android.view.View;
import android.view.ViewGroup;
import eu.vranckaert.calendar.R;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class MonthView extends ViewGroup {
    private static final int ROWS = 6;
    private static final int COLUMNS = 7;
    private MonthGrid mMonthGrid;

    public MonthView(Context context) {
        this(context, null);
    }

    public MonthView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MonthView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs);
    }

    private void ensureChildren() {
        mMonthGrid = (MonthGrid) findViewById(R.id.calendar_month_view);
        if (mMonthGrid == null) {
            throw new IllegalStateException("Must include a R.id.calendar_month_view view.");
        }
        mMonthGrid.setDrawingCacheEnabled(true);
    }

    /**
     * Remove any {@link com.realdolmen.trm.util.ui.cal.widget.BlockView} instances, leaving only
     * {@link com.realdolmen.trm.util.ui.cal.widget.TimeRulerView} remaining.
     */
    public void removeAllCells() {
        ensureChildren();
        removeAllViews();
        addView(mMonthGrid);
    }

    public void addCell(MonthCellView monthCellView) {
        monthCellView.setDrawingCacheEnabled(true);
        monthCellView.requestLayout();
        addView(monthCellView, 1);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        ensureChildren();

        mMonthGrid.measure(widthMeasureSpec, heightMeasureSpec);

        final int width = mMonthGrid.getMeasuredWidth();
        final int height = mMonthGrid.getMeasuredHeight();

        setMeasuredDimension(resolveSize(width, widthMeasureSpec),
                resolveSize(height, heightMeasureSpec));
    }

    public List<MonthCellView> buildCalendarCells(final Date date, final int weekStartDay, final MonthCellView.CellViewClickListener cellViewClickListener, final Activity context) {
        List<MonthCellView> monthCellViews = new ArrayList<MonthCellView>();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        MonthDisplayHelper displayHelper = new MonthDisplayHelper(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), weekStartDay);

        for (int r=0; r<ROWS; r++) {
            int[] digits = displayHelper.getDigitsForRow(r);

            for (int c=0; c<digits.length; c++) {
                boolean isWithinCurrentMonth = displayHelper.isWithinCurrentMonth(r, c);

                Calendar currentDay = Calendar.getInstance();
                currentDay.setTime(date);
                if (!isWithinCurrentMonth) {
                    if (r<3) {
                        // Previous Month
                        currentDay.add(Calendar.MONTH, -1);
                    } else {
                        // Next Month
                        currentDay.add(Calendar.MONTH, 1);
                    }
                }
                currentDay.set(Calendar.DAY_OF_MONTH, digits[c]);

                MonthCellView monthCellView = (MonthCellView) context.getLayoutInflater().inflate(R.layout.cal__mont_cell, null);
                monthCellView.init(currentDay.getTime(), isWithinCurrentMonth, r, c, cellViewClickListener);
                addCell(monthCellView);
                monthCellViews.add(monthCellView);
            }
        }

        return monthCellViews;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        ensureChildren();

        final MonthGrid monthGrid = mMonthGrid;

        monthGrid.layout(0, 0, getWidth(), getHeight());

        final int rowHeight = getHeight() / ROWS;
        final int columnWidth = getWidth() / COLUMNS;

        final int count = getChildCount();
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() == GONE) continue;

            if (child instanceof MonthCellView) {
                final MonthCellView monthCellView = (MonthCellView) child;
                final int top = monthCellView.getRow() * rowHeight + 1;
                final int bottom = top + rowHeight - 1;
                final int left = monthCellView.getColumn() * columnWidth + 1;
                final int right = left + columnWidth - 1;
                monthCellView.layout(left, top, right, bottom);
            }
        }
    }
}